﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChapterX.BusinessFacade;
using ChapterX.Common;
using ChapterX.Data;
using ChapterX.Data.BooksDSTableAdapters;
using System.Data;
using ChapterX.Data.CoursesDSTableAdapters;

namespace ChapterX.Modules
{
    public partial class BookEntryModule : ChapterX.Model.ModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Utils.HasValue(Request.QueryString[QueryKeys.BOOK_ID]))
                {
                    Field_BookId.Value = Utils.GetValue(Request.QueryString[QueryKeys.BOOK_ID]);
                    Delete.Visible = true;
                }
                else
                {
                    Field_BookId.Value = String.Empty;
                    Delete.Visible = false;
                }

                if (CurrentUserInfo.IsTeacher)
                {
                    Row_TeacherId.Visible = false;
                }

                BindBook();
                BindUnboundCourseList();
            }
        }

        protected void BindBook()
        {
            int bookId;

            if (Utils.HasValue(Field_BookId.Value) && Int32.TryParse(Field_BookId.Value, out bookId))
            {
                try
                {
                    BookSystem bs = new BookSystem();
                    BooksDS.BooksRow book = bs.GetBookByBookId(bookId);

                    if (null == book)
                    {
                        throw new RecordNotExistedException();
                    }

                    Field_Title.Text = Utils.FilterHtml(book.Title);
                    Field_AuthorEditor.Text = Utils.FilterHtml(book.AuthorEditor);
                    if (!book.IsISBNNull())
                    {
                        Field_ISBN.Text = Utils.FilterHtml(book.ISBN);
                    }
                    if (!book.IsPublisherNull())
                    {
                        Field_Publisher.Text = Utils.FilterHtml(book.Publisher);
                    }
                    if (!book.IsPubPlaceNull())
                    {
                        Field_PubPlace.Text = Utils.FilterHtml(book.PubPlace);
                    }
                    if (!book.IsPubYearNull())
                    {
                        Field_PubYear.Text = book.PubYear.ToString();
                    }
                    if (!book.IsEditionNull())
                    {
                        Field_Edition.Text = Utils.FilterHtml(book.Edition);
                    }
                    Field_TeacherId.Text = book.TeacherId;
                }
                catch (Exception ex)
                {
                    SetErrorMessage(ex.Message);
                    Logger.Log(ex);
                }
            }
            else
            {
                if (CurrentUserInfo.IsTeacher)
                {
                    Field_TeacherId.Text = CurrentUserInfo.Username;
                }
            }
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                BookSystem bs = new BookSystem();
                BooksDS.BooksRow book = bs.BookSchema.NewBooksRow();

                if (Utils.HasValue(Field_BookId.Value))
                {
                    try
                    {
                        book.BookId = Int32.Parse(Utils.GetValue(Field_BookId.Value));
                    }
                    catch
                    {
                        throw new UnexpectedException();
                    }
                }
                else
                {
                    book.BookId = -1;
                }

                book.Title = Field_Title.Text;
                book.AuthorEditor = Field_AuthorEditor.Text;
                book.ISBN = Field_ISBN.Text;
                book.Publisher = Field_Publisher.Text;
                book.PubPlace = Field_PubPlace.Text;
                if (Utils.HasValue(Field_PubYear.Text))
                {
                    try
                    {
                        book.PubYear = Utils.ParseInt32(Utils.GetValue(Field_PubYear.Text), 1900, DateTime.Now.Year + 1);
                    }
                    catch
                    {
                        throw new InvalidInputException("字段值无效：出版年");
                    }
                }
                book.Edition = Field_Edition.Text;
                book.TeacherId = Field_TeacherId.Text;

                result = bs.SubmitBook(book, CurrentUserInfo.Username);

                if (result)
                {
                    SetInfoMessage("教材信息提交成功。");
                    BindBook();
                }
                else
                {
                    SetErrorMessage("教材信息提交失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                Logger.Log(ex);
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                BookSystem cs = new BookSystem();

                result = cs.DeleteBook(Int32.Parse(Field_BookId.Value));

                if (result)
                {
                    SetInfoMessage("教材信息删除成功。");
                }
                else
                {
                    SetErrorMessage("教材信息删除失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                Logger.Log(ex);
            }
        }


        protected void BindUnboundCourseList()
        {
            //temp，假设当前用户为teacher，根据teacherid拉取课程列表
            
            try
            {
                TeacherCourseViewTableAdapter adapter = new TeacherCourseViewTableAdapter();
                DataTable courseList = null;

                if (CurrentUserInfo.IsTeacher)
                {
                    courseList = adapter.GetCourseListByTeacherId(CurrentUserInfo.Username);
                }
                else
                {
                    courseList = adapter.GetData();
                }

                this.UnboundCourseList.DataSource = courseList.DefaultView;
                this.UnboundCourseList.DataValueField = "CourseId";
                this.UnboundCourseList.DataTextField = "CourseName";
                this.UnboundCourseList.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("数据绑定失败。");
                Logger.Log(ex);
            }
        }


        protected void BindCourse_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                CourseSystem cs = new CourseSystem();

                result = cs.BindCourseBook(Int32.Parse(this.UnboundCourseList.SelectedValue),
                    Int32.Parse(Field_BookId.Value), "教材");

                if (result)
                {
                    SetInfoMessage("课程绑定成功。");
                }
                else
                {
                    SetErrorMessage("课程绑定失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage("课程绑定失败。");
                Logger.Log(ex);
            }
        }
    }
}